package com.car.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.car.entity.Carrentalorderform;
import com.car.entity.Detailedlistofrentalcharges;
import com.car.entity.User;
import com.car.page.Page;
import com.car.service.CardetailstableService;
import com.car.service.CarrentalorderformService;
import com.car.service.CouponService;
import com.car.service.DetailedlistofrentalchargesService;
import com.car.service.UserService;
import com.car.service.VehiclemotioncarService;
import com.car.service.send.OrderTimeoutProducer;
import com.car.util.SUKUtil;
import com.car.util.voiceUtil;
import com.car.vo.CarrentalorderformVo;
import com.car.vo.CartableVo;
import com.car.vo.DetailedlistofrentalchargesVo;
import com.car.vo.VehiclemotioncarVo;
import com.car.vo.orderVo;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/order")
public class CarrentalorderformController {

	Map<String, Object> maps = new HashMap<>();

	@Autowired
	CarrentalorderformService carrentalorderformService;
	@Autowired
	DetailedlistofrentalchargesService detailedlistofrentalchargesService;
	@Autowired
	VehiclemotioncarService vehiclemotioncarService;
	@Autowired
	OrderTimeoutProducer orderTimeoutProducer;
	@Autowired
	CardetailstableService carDetailService;
	
	@Autowired
	CouponService coiponService;
	@Autowired
	UserService userService;
	
	
	@RequestMapping("/ali")
	public void ali(HttpServletResponse response, HttpServletRequest request,HttpSession session) throws IOException, AlipayApiException{
		carrentalorderformService.ali(response, request,session.getAttribute("ordersIdAddToPay").toString(),Integer.parseInt(session.getAttribute("theRent").toString()));
	}

	/**
	 * 
	 * @Title: addOrder @Description: TODO(添加订单) @param: @return @return:
	 *         int @throws
	 */
	@ResponseBody
	@RequestMapping("/addOrder")
	public String addOrder(DetailedlistofrentalchargesVo detaillist, HttpSession session) {
		SUKUtil util = new SUKUtil();
		User user = (User) session.getAttribute("loginSuccess");
		CartableVo car = (CartableVo) session.getAttribute("carinfos");
		String qcsm=session.getAttribute("qcsm").toString();
		String scsm=session.getAttribute("scsm").toString();
		Map<String, String> time = new HashMap();
		String mycity=session.getAttribute("myCity").toString();
		String hcmycity=session.getAttribute("hcmycity").toString();
		time.put("qctime", (String) session.getAttribute("qcTime"));
		time.put("hctime", (String) session.getAttribute("hcTime"));
		String qccity = session.getAttribute("qccity").toString();
		String hccity = session.getAttribute("hccity").toString();
		orderVo orderbo = new orderVo(user, car, time, qccity, hccity, scsm, qcsm);
		CarrentalorderformVo order = new CarrentalorderformVo();
		order.setTakeCarcity(mycity);
		order.setCarCity(hcmycity);
		int i = carrentalorderformService.addOrder(orderbo, detaillist,order);
		int update=carDetailService.updateByCarId(order.getCarId());
		if(update!=0){
			return JSON.toJSONString(order.getOrderId());
		}
		return "";

	}

	/**
	 * 订单 @Title: userIdToOrders @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param orderState @param @param
	 * pageNo @param @param pageSize @param @param session @param @param
	 * model @param @return 参数 @return String 返回类型 @throws
	 */
	@RequestMapping("/orderInfo")
	public String userIdToOrders(@RequestParam(value = "orderState", required = false) Integer orderState,
			@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageNo,
			@RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize,
			HttpSession session, Model model) {
		User user = (User) session.getAttribute("loginSuccess");
		Page<CarrentalorderformVo> page = carrentalorderformService.selectAllbyuserId(user.getUserId(), orderState,
				pageNo, pageSize);
		int counts = carrentalorderformService.selectAllbyuserIdToCount(user.getUserId(), orderState);
		Date date1 = new Date();
		Date date2 = new Date();
		int days = 0;
		if (!page.getList().isEmpty()) {
			date1 = page.getList().get(0).getVehicleTakingTime();
			date2 = page.getList().get(0).getReturnTime();
			days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
		}
		if (orderState == null) {
			orderState = 0;
		}
		model.addAttribute("page", page);
		model.addAttribute("orderState", orderState);
		model.addAttribute("count", counts);
		model.addAttribute("orderList", page.getList().isEmpty() ? null : page.getList());
		model.addAttribute("qiTime", date1.getHours() + ":" + date1.getMinutes());
		model.addAttribute("huanTime", date2.getHours() + ":" + date2.getMinutes());
		model.addAttribute("days", days);
		model.addAttribute("pageIndex", pageNo);
		return "H5phone/carOrders";
	}

	/**
	 * 订单详情 @Title: userIdToOrdersInfos @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param orderId @param @param
	 * session @param @param model @param @return 参数 @return String 返回类型 @throws
	 */
	@RequestMapping("/orderInfos")
	public String userIdToOrdersInfos(@RequestParam("orderId") String orderId, @RequestParam("orderS") String orderS,
			@RequestParam(value = "pageIndex", required = false,defaultValue="0") Integer pageIndex,
			@RequestParam(value = "i", required = false) Integer i, HttpSession session, Model model) {
		if (pageIndex == 0) {
			pageIndex = 1;
		}
		if (i == null) {
			i = 0;
		}
		CarrentalorderformVo carr = carrentalorderformService.selectAllToInfos(orderId, i);
		DetailedlistofrentalchargesVo detaile = detailedlistofrentalchargesService.selectByPrimaryKey(orderId);
		Date date1 = new Date();
		Date date2 = new Date();
		int days = 0;
		date1 = carr.getVehicleTakingTime();
		date2 = carr.getReturnTime();
		days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		int month = cal.get(Calendar.MONTH);
		int dayy = cal.get(Calendar.DATE);
		String qi = ((month + 1) + "-" + dayy);
		cal.setTime(date2);
		int month1 = cal.get(Calendar.MONTH);
		int dayy1 = cal.get(Calendar.DATE);
		String huan = ((month1 + 1) + "-" + dayy1);
		model.addAttribute("huan", huan);
		model.addAttribute("i", i);
		model.addAttribute("qi", qi);
		model.addAttribute("ors", orderS);
		model.addAttribute("detaileMoney", detaile.getTotal());
		model.addAttribute("qiTime", date1.getHours() + ":" + date1.getMinutes());
		model.addAttribute("huanTime", date2.getHours() + ":" + date2.getMinutes());
		model.addAttribute("carr", carr);
		model.addAttribute("days", days);
		model.addAttribute("pageIndex", pageIndex);
		return "H5phone/carOrderInfo";
	}

	/**
	 * 修改订单跳转{取消} @Title: updOrderFrom @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @return 参数 @return String 返回类型 @throws
	 */
	@RequestMapping("/updStare")
	public String updOrderFrom(String orderId, String names, Model model) {
		model.addAttribute("orders", orderId);
		model.addAttribute("names", names);
		return "H5phone/cancelOrder";
	}

	/**
	 * 修改订单状态 @Title: updOrderFrom @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @return 参数 @return String 返回类型 @throws
	 */
	@RequestMapping("/updStareInfo")
	@ResponseBody
	public Map<String, Object> updOrder(String orderId) {
		int nums = carrentalorderformService.updOrderState("8", orderId);
		maps.put("msg", nums > 0 ? true : false);
		return maps;
	}

	/**
	 * 順風車订单 @Title: userIdToOrders @Description:
	 * TODO(这里用一句话描述这个方法的作用) @param @param orderState @param @param
	 * pageNo @param @param pageSize @param @param session @param @param
	 * model @param @return 参数 @return String 返回类型 @throws
	 */
	@RequestMapping("/shunCarOrder")
	public String ToShunOrder(@RequestParam(value = "orderState", required = false) Integer orderState,
			@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageNo,
			@RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize,
			HttpSession session, Model model) {
		User user = (User) session.getAttribute("loginSuccess");
		Page<CarrentalorderformVo> page = carrentalorderformService.selectAllbyuserIdTwo(user.getUserId(), orderState,
				pageNo, pageSize);
		int counts = carrentalorderformService.selectAllbyuserIdToCountShun(user.getUserId(), orderState);
		Date date1 = new Date();
		Date date2 = new Date();
		int days = 0;
		if (!page.getList().isEmpty()) {
			date1 = page.getList().get(0).getVehicleTakingTime();
			date2 = page.getList().get(0).getReturnTime();
			days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
		}
		if (orderState == null) {
			orderState = 0;
		}
		model.addAttribute("page", page);
		model.addAttribute("orderState", orderState);
		model.addAttribute("count", counts);
		model.addAttribute("orderList", page.getList().isEmpty() ? null : page.getList());
		model.addAttribute("qiTime", date1.getHours() + ":" + date1.getMinutes());
		model.addAttribute("huanTime", date2.getHours() + ":" + date2.getMinutes());
		model.addAttribute("days", days);
		model.addAttribute("pageIndex", pageNo);
		return "H5phone/shunCarOrder";
	}

	/**
	 * 訂單添加 @Title: AddOrder @Description: TODO(这里用一句话描述这个方法的作用) @param @return
	 * 参数 @return String 返回类型 @throws
	 */
	@RequestMapping("/addOrders")
	public String AddOrder(
			@RequestParam(value = "hitid", required = false) Integer hitid,
			@RequestParam(value = "quTime", required = false) String quTime,
			@RequestParam(value = "huanTime", required = false) String huanTime,
			@RequestParam(value = "huanmd", required = false) String huanmd,
			@RequestParam(value = "orderId", required = false) String orderId,
			@RequestParam(value = "couponId", required = false) String couponId,
			@RequestParam(value = "amountOfCoupon", required = false) Integer amountOfCoupon,
			@RequestParam(value = "addTypes", required = false) Integer addTypes, //判断是否是第一次进入
			HttpSession session,Model model){
		User users = (User) session.getAttribute("loginSuccess");
		User user = userService.selectByPrimaryKey(users.getUserId());
		VehiclemotioncarVo vehiclemotioncarVo = vehiclemotioncarService.selectById(hitid);
		if(orderId==null){
		if(addTypes==null){
			Carrentalorderform record = new Carrentalorderform();
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			 try {
				record.setVehicleTakingTime(sdf.parse(quTime)); 
				record.setReturnTime(sdf.parse(huanTime));
				record.setActualVehicleTakingTime(sdf.parse(quTime));
				record.setActualTransferTime(sdf.parse(huanTime));
				record.setTheDoorPoint(huanmd);
				
				record.setUserId(users.getUserId());
				
				int nums = carrentalorderformService.insert(record,vehiclemotioncarVo,new Detailedlistofrentalcharges());
			
				int count = coiponService.countByUserId(user.getUserId());
				if(nums>0){
					orderTimeoutProducer.sendMessage(record.getOrderId());
				}
				session.setAttribute("ordersIdAddToPay", record.getOrderId());//新增的id
				
				model.addAttribute("count", count);
				model.addAttribute("userId", user.getUserId());
				Map<String, Object> maps = new HashMap<>();
				maps.put("hitid", hitid);
				maps.put("quTime", quTime);
				maps.put("huanTime", huanTime);
				maps.put("huanmd", huanmd);
				session.setAttribute("mapsToOrderAdd", maps);
				session.setAttribute("couponId", "");//优惠卷Id
				session.setAttribute("amountOfCoupon", "");//优惠卷金额
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		}else{
			int count = coiponService.countByUserId(user.getUserId());
			model.addAttribute("count", count);
			model.addAttribute("userId", user.getUserId());
		}
		}
		//orderId是从订单页面过来的
		if(orderId!=null){
			session.setAttribute("ordersIdAddToPay", orderId);//从订单页面过来
			int count = coiponService.countByUserId(user.getUserId());
			model.addAttribute("count", count);
			model.addAttribute("userId", user.getUserId());
			Map<String, Object> maps = new HashMap<>();
			maps.put("hitid", hitid);
			maps.put("quTime", quTime);
			maps.put("huanTime", huanTime);
			maps.put("huanmd", huanmd);
			session.setAttribute("mapsToOrderAdd", maps);
		}
		
		if(couponId!=null && amountOfCoupon!=null){
			session.setAttribute("couponId", couponId);//优惠卷Id
			session.setAttribute("amountOfCoupon", amountOfCoupon);//优惠卷金额
		}
			
		if(amountOfCoupon!=null){
			session.setAttribute("theRent",vehiclemotioncarVo.getTheRent()*vehiclemotioncarVo.getDays()/2-amountOfCoupon );//价格
		}else{
			session.setAttribute("theRent",vehiclemotioncarVo.getTheRent()*vehiclemotioncarVo.getDays()/2);//价格
		}
		
		return "H5phone/pay";
	}

	@RequestMapping("/toPay")
	public String  pay(@RequestParam(value="out_trade_no")String orderId,
						@RequestParam(value="total_amount")String money,
						@RequestParam(value="timestamp")String timestamp
						,Model model,HttpSession session){
			if(orderId!=null){
			int nums =carrentalorderformService.updOrderState("9", orderId);
			//删除相对应的优惠卷
			//2018年12月15日 17:23:49  删除需要测试
			String couponId =session.getAttribute("couponId").toString();
			if(couponId!=""){
				coiponService.deleteByPrimaryKey(Integer.parseInt(couponId));
			}
		
			String amountOfCoupon =session.getAttribute("amountOfCoupon").toString();//拿到优惠卷价格
			if(amountOfCoupon!=""){
			 Integer amountOfCoupo = Integer.parseInt(amountOfCoupon);
			double moneys =Double.parseDouble(money);
			//修改优惠卷需要测试
			Integer mon_amountCoupo =(int)moneys;
			detailedlistofrentalchargesService.updTotalAndCouponUsageToOrderId(mon_amountCoupo,amountOfCoupo,orderId);
			String content="您已成功支付"+mon_amountCoupo+"元,您的订单号为"+orderId;
			voiceUtil.voice(content);
			//更改订单的优惠卷使用金额
			model.addAttribute("msg", nums>0?1:0);
			}else{
				String content="您已成功支付"+money+"元,您的订单号为"+orderId;
				voiceUtil.voice(content);
				//更改订单的优惠卷使用金额
				model.addAttribute("msg", nums>0?1:0);
			}
			
		}	
		model.addAttribute("orderId", orderId);
		model.addAttribute("timestamp", timestamp);
		
		return "H5phone/showpayType";
	}

}